package models

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"
	"github.com/pquerna/ffjson/ffjson"
	"strconv"
	"time"
)

var pageconfigcache, _ = cache.NewCache("memory", `{"interval":600}`)
var cachePrefix = "pageconfig"

const pageConfigCachTime = 600 * time.Second

var AlMap map[string]interface{}

type PageConfig struct {
	Id             int64  `form:"id" orm:"column(id)" json:"id"`
	ConfigId       string `form:"configId" orm:"column(configId)" json:"configId"`
	ConfigJson     string `form:"configJson" orm:"column(configJson)" json:"configJson"`
	CreateTime     string `form:"createtime" orm:"column(createtime)" json:"createtime"`
	LastModifyTime string `form:"lastmodifytime" orm:"column(lastmodifytime)" json:"lastmodifytime"`
}
type ConfigItem struct {
	Field      string `json:"field"`
	Name       string `json:"name"`
	Type       string `json:"type"`
	Options    string `json:"options"`
	AllowBlank string `json:"allowblank"`
	ReadOnly   string `json:"readonly"`
	MaxLength  int    `json:"maxlength"`
	Width      string `json:"width"`
	Height     string `json:"height"`
}
type ConfigItems struct {
	Field      []string `form:"field" orm:"column(field)" json:"field"`
	Name       []string `form:"name" orm:"column(name)" json:"name"`
	AllowBlank []string `form:"allowblank" orm:"column(allowblank)" json:"allowblank"`
	ReadOnly   []string `form:"readonly" orm:"column(readonly)" json:"readonly"`
	Type       []string `form:"type" orm:"column(type)" json:"type"`
	Options    []string `form:"options" orm:"column(options)" json:"options"`
	MaxLength  []int    `form:"maxlength" orm:"column(maxlength)" json:"maxlength"`
	Width      []string `form:"width" orm:"column(width)" json:"width"`
	Height     []string `form:"height" orm:"column(height)" json:"height"`
}
type AIStruct struct {
	LeftRatio  string `form:"left_ratio" json:"left_ratio"`
	RightRatio string `form:"right_ratio" json:"right_ratio"`
	GPU        string `form:"gpu" json:"gpu"`
	HostIp     string `form:"host_ip" json:"host_ip"`
	WorkPath   string `form:"work_path" json:"work_path"`
}

type ConfigAlgorithm struct {
	AID    string `orm:"column(AID);size(45)" json:"AID" form:"AID"`
	AIName string `orm:"column(AIName);" json:"AIName" form:"AIName"`
	AIType string `orm:"column(AIType);" json:"AIType" form:"AIType"`
	DataNo string `orm:"column(DataNo);" json:"DataNo" form:"DataNo"`
}

func (t *PageConfig) TableName() string {
	return "page_config"
}

func init() {
	orm.RegisterModel(new(PageConfig))
}
func ClearCache() error {
	return pageconfigcache.ClearAll()
}
func AddPageConfig(m *PageConfig) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	if err == nil {
		m.Id = id
		key := cachePrefix + strconv.FormatInt(id, 10)
		pageconfigcache.Put(key, m, pageConfigCachTime)
		configIdkey := cachePrefix + m.ConfigId
		n := m
		pageconfigcache.Put(configIdkey, n, pageConfigCachTime)
	}
	return
}
func ClearPageConfigCacheById(id int64) {
	key := cachePrefix + strconv.FormatInt(id, 10)
	pageconfigcache.Delete(key)
}

func ClearPageConfigCachByConfigId(configId string) {
	key := cachePrefix + configId
	pageconfigcache.Delete(key)
}
func GetPageConfigById(id int64) (v *PageConfig, err error) {
	key := cachePrefix + strconv.FormatInt(id, 10)
	if pageconfigcache.IsExist(key) {
		pconfig := pageconfigcache.Get(key)
		v = pconfig.(*PageConfig)
		err = nil
	} else {
		o := orm.NewOrm()
		v1 := &PageConfig{Id: id}
		if err = o.Read(v1); err == nil {
			v = v1
			pageconfigcache.Put(key, v, pageConfigCachTime)
		}
	}
	return
}

func GetPageConfigByConfigId(configId string) (v *PageConfig, err error) {
	key := cachePrefix + configId
	if pageconfigcache.IsExist(key) {
		pconfig := pageconfigcache.Get(key)
		v = pconfig.(*PageConfig)
		err = nil
	} else {
		o := orm.NewOrm()
		err = o.Raw("select * from page_config where configId=?", configId).QueryRow(&v)
		if err == nil {
			pageconfigcache.Put(key, v, pageConfigCachTime)
		}
	}
	return
}
func UpdatePageConfigById(m *PageConfig) (err error) {
	o := orm.NewOrm()
	v := &PageConfig{Id: m.Id}
	if err = o.Read(v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			ClearPageConfigCacheById(m.Id)
			key := cachePrefix + strconv.FormatInt(m.Id, 10)
			pageconfigcache.Put(key, m, pageConfigCachTime)
			ClearPageConfigCachByConfigId(m.ConfigId)
			configIdkey := cachePrefix + m.ConfigId
			pageconfigcache.Put(configIdkey, m, pageConfigCachTime)
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
func DeletePageConfig(id int64) (err error) {
	o := orm.NewOrm()
	v := PageConfig{Id: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&PageConfig{Id: id}); err == nil {
			ClearPageConfigCacheById(id)
			ClearPageConfigCachByConfigId(v.ConfigId)
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
func GetAllPageConfig(fields []string) (l []*PageConfig, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(PageConfig))
	sortFields := []string{"-id"}
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.All(&l, fields...); err != nil {
		return nil, err
	}
	return
}

func GetConfigData(tableName string) (ds []*interface{}, err error) {
	o := orm.NewOrm()
	_, err = o.Raw("SELECT * FROM " + tableName).QueryRows(&ds)
	return
}

func GetAddContent(configId string) (addItem []string) {
	pageConfig, err := GetPageConfigByConfigId(configId)
	if err != nil {
		beego.Error(err)
		return
	}
	configJson := pageConfig.ConfigJson
	var m []map[string]interface{}
	ffjson.Unmarshal([]byte(configJson), &m)
	for i := 0; i < len(m); i++ {
		configItem := m[i]
		if configItem["type"].(string) != "button" {
			addItem = append(addItem, configItem["field"].(string))
		}

	}
	return
}
